package com.czy.owner.ui;

import android.Manifest;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.czy.owner.R;
import com.czy.owner.api.GetMallStatusApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.ChainStoresModel;
import com.czy.owner.entity.WebViewRequestParam;
import com.czy.owner.entity.generator.DataGenerator;
import com.czy.owner.global.Constants;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.net.utils.JsonUtil;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.services.GetuiPushService;
import com.czy.owner.ui.order.ProjectDetailsWebviewActivity;
import com.czy.owner.utils.GetDeviceId;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.NotifyUtil;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.RxDeviceTool;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.StatusBarUtil;
import com.czy.owner.widget.MyEditText;
import com.easemob.cases.MessageHelper;
import com.hyphenate.EMGroupChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.igexin.sdk.PushManager;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.analytics.MobclickAgent;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.functions.Consumer;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;

import static com.czy.owner.entity.WebViewRequestParam.REQUEST_POST;


/**
 * Created by wangyang on 2017/5/18 0018.
 * 未绑定首页
 */

public class MainActivity extends BaseActivity implements TabHost.OnTabChangeListener {
    public static boolean isMainActivity = true;
    private Fragment[] mFragments;
    private FragmentTabHost mTabHost;
    private Badge badge;
    //    当前选中的views的下标
    private int currentIndex = 0;
    private List<Integer> showFragmentIndex = new ArrayList<>();
    private long exitTime = 0;
    public static boolean isNeedBind = false;
    public static boolean refreshShopping = false;
    private RxPermissions rxPermissions;
    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_tab_host_layout;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        RxBus.getDefault().register(this);
        rxPermissions = new RxPermissions(MainActivity.this);
        UserHelper.getInstance().setCloseMall(false);
        selectedStoreId();
        StatusBarUtil.setTranslucentForImageViewInFragment(MainActivity.this, null);
        if (UserHelper.getInstance().isLogined() && UserHelper.getInstance().getSelectStoreId() > 0) {
            isMall();
        } else {
            loadMain();
        }


        if ((Build.VERSION.SDK_INT >= 23)) {
            getPermissions();
        } else {
            initLoc();
        }


    }
//        MyLog.e("yang","系统版本=="+ RxDeviceTool.getSystemVersion());
//        MyLog.e("yang","设备型号=="+ RxDeviceTool.getBuildBrandModel());
//        MyLog.e("yang","设备厂商=="+ RxDeviceTool.getBuildMANUFACTURER());
//        MyLog.e("yang","设备品牌=="+ RxDeviceTool.getBuildMANUFACTURER());
//        MyLog.e("yang","设备mac地址=="+ RxDeviceTool.getMacAddress(MainActivity.this));
//        MyLog.e("yang","运营商=="+ RxDeviceTool.getSimOperatorName(MainActivity.this));

//    pid	是	string	设备唯一识别号
//    appName	是	string	app名称，袋鼠车管家，袋鼠店管家，袋鼠助手
//    appVersion	是	string	当前软件版本号，1.7，1.7.4 …
//    system	是	string	系统类型，android，ios
//    systemVersion	是	string	系统版本号,android的版本，ios版本
//    model	是	string	手机型号，如 vivo x9
//    vendor	是	string	手机厂商，如 vivo
//    brand	是	string	手机品牌，如vivo
//    session	否	string	用户登录session，如果登录了就必须传
//    mac	否	string	mac地址，android需要传
//    operator	否	string	手机运营商,如果能获取到就必须传
//    gpsLng	否	double	GPS经度，如果能获取到就必须传
//    gpsLat	否	double	GPS纬度，如果能获取到就必须传



    private void bigDataAppInfo(){
        GetDeviceId getDeviceId = new GetDeviceId(MainActivity.this);
        String url  = Constants.APP_API_BASE + Constants.BIGDATA_APP_LOGIN;
        RequestParams params = new RequestParams(url);
        try {
            params.addBodyParameter("pid",getDeviceId.getCombinedId());
        }catch (Exception e){
           MyLog.e("yang","pid异常=="+e.toString());
        }
        params.addBodyParameter("appName","袋鼠车管家");
        params.addBodyParameter("appVersion",PhoneUtils.getVersion(MainActivity.this)+"");
        params.addBodyParameter("system","android");
        params.addBodyParameter("systemVersion",RxDeviceTool.getSystemVersion()+"");
        params.addBodyParameter("model",RxDeviceTool.getBuildBrandModel()+"");
        params.addBodyParameter("vendor",RxDeviceTool.getBuildMANUFACTURER()+"");
        params.addBodyParameter("brand", RxDeviceTool.getBuildMANUFACTURER()+"");
        params.addBodyParameter("session",UserHelper.getInstance().getSession(MainActivity.this));
        params.addBodyParameter("mac",RxDeviceTool.getMacAddress(MainActivity.this)+"");
        params.addBodyParameter("operator",RxDeviceTool.getSimOperatorName(MainActivity.this)+"");
        params.addBodyParameter("gpsLng",longItude+"");
        params.addBodyParameter("gpsLng",latItude+"");
        MyLog.e("yang","手机信息params=="+params.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang","onSuccess手机数据=="+result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang","onError手机数据=="+ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    public void getPermissions() {
        rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.READ_PHONE_STATE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            initLoc();
                            MyLog.e("yang", "获取权限成功");
                        } else {
                            MyLog.e("yang", "获取权限失败");

                        }
                    }
                });
    }



    private void isMall() {
        String url = Constants.APP_API_BASE + Constants.OWN_GET_MALL_STATUS;
        RequestParams params = new RequestParams(url);
        params.addBodyParameter("session", UserHelper.getInstance().getSession(this));
        params.addBodyParameter("storeId", SharedPreferencesUtils.getParam(MainActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                boolean myMall = JsonUtil.getJsonValuesBoolean(result, "data");
                MyLog.e("yang", "isMall==" + myMall);
                UserHelper.getInstance().setCloseMall(!myMall);
                loadMain();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "onError==" + ex.toString());
                loadMain();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private void loadMain() {
        mFragments = DataGenerator.getFragments();

        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        // 关联TabHost
        mTabHost.setup(this, getSupportFragmentManager(), R.id.home_container);
        //注意，监听要设置在添加Tab之前
        mTabHost.setOnTabChangedListener(this);

        if (UserHelper.getInstance().isCloseMall()) {
            showFragmentIndex.add(2);
            showFragmentIndex.add(1);
            showFragmentIndex.add(5);
            showFragmentIndex.add(4);
        } else {
            showFragmentIndex.add(0);
            showFragmentIndex.add(1);
            showFragmentIndex.add(2);
            showFragmentIndex.add(3);
            showFragmentIndex.add(4);
        }
        //添加Tab
        for (int i = 0; i < showFragmentIndex.size(); i++) {
            //生成TabSpec
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(DataGenerator.mTabTitle[showFragmentIndex.get(i)]).setIndicator(DataGenerator.getTabView(this, showFragmentIndex.get(i)));
            // 添加Tab 到TabHost，并绑定Fragment
            Bundle bundle = mFragments[showFragmentIndex.get(i)].getArguments();
            if (bundle == null) {
                bundle = new Bundle();
            }
            bundle.putString("from", "FragmentTabHost Tab");
            mTabHost.addTab(tabSpec, mFragments[showFragmentIndex.get(i)].getClass(), bundle);
        }


        //去掉Tab 之间的分割线
        mTabHost.getTabWidget().setDividerDrawable(null);
//      默认选择第一个tab
        boolean isStoreBind = (Boolean) SharedPreferencesUtils.getParam(MainActivity.this, Constants.SHARED_PREFERENCES_KEY_IS_STORE_BIND, false);
        if (!UserHelper.getInstance().isCloseMall()) {
            if (isStoreBind) {
                MyLog.e("yang", "isStoreBind===" + isStoreBind);
                mTabHost.setCurrentTab(2);
                refreshShopping = true;
            } else {
                mTabHost.setCurrentTab(0);
            }
        } else {
            if (isStoreBind) {
                MyLog.e("yang", "isStoreBind===" + isStoreBind);
                mTabHost.setCurrentTab(2);
                refreshShopping = true;
            } else {
                mTabHost.setCurrentTab(0);
            }
        }

        //Log.i("GetuiPushService", "initialize");
        //PackageManager pkgManager = getPackageManager();

        /*// 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
        boolean sdCardWritePermission =
                pkgManager.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        // read phone state用于获取 imei 设备信息
        boolean phoneSatePermission =
                pkgManager.checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if (Build.VERSION.SDK_INT >= 23 && !sdCardWritePermission || !phoneSatePermission) {
            requestPermission();
        } else {
            PushManager.getInstance().initialize(this.getApplicationContext(), GetuiPushService.class);
        }*/

        //PushManager.getInstance().initialize(this.getApplicationContext(), GetuiPushService.class);
        //PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), GetuiIntentService.class);
        //String cid = PushManager.getInstance().getClientid(this);
        //Log.d("GetuiPushService", "当前应用的cid = " + cid);

        badge = new QBadgeView(this).bindTarget(mTabHost.getTabWidget().getChildTabViewAt(1)).setBadgeNumber(0).setGravityOffset(19, 0, true)
                .setBadgePadding(2, true).setBadgeBackgroundColor(ContextCompat.getColor(this, R.color.appThemeNewsColor)).setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
                    @Override
                    public void onDragStateChanged(int dragState, Badge badge, View targetView) {
                        if (dragState == STATE_SUCCEED) {
                            EMClient.getInstance().chatManager().markAllConversationsAsRead();
                            refreshUIWithMessage();
                        }
                    }
                });
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
        EMClient.getInstance().groupManager().addGroupChangeListener(groupChangeListener);
    }

    /**
     * 通知栏
     */
    private int requestCode = (int) SystemClock.uptimeMillis();

    private void notify_normal_singLine(String data) {
//        if (mFragments[2] != null) {
//            try {
//                StoreFragment storeFragment = (StoreFragment) mFragments[2];
//                storeFragment.getBulletin(this);
//            }catch (Exception e){
//                MyLog.e("hep",e.getMessage().toString());
//            }
//
//        }
        MyLog.e("hep", data.toString());
        WebViewRequestParam webViewRequestParam = new WebViewRequestParam(Constants.APP_API_BASE + Constants.OWN_BULLETIN);
        webViewRequestParam.setRequestMethod(REQUEST_POST);
        webViewRequestParam.setParams("session=" + UserHelper.getInstance().getSessionInfoModel(
                this).getSession() + "&storeId=" + (SharedPreferencesUtils.getParam(this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "") +
                "&infoId=" + JsonUtil.getJsonValuesString(data, "infoId")
        );
//        MyLog.e("hedepu", "session=" + UserHelper.getInstance().getSessionInfoModel(
//                this).getSession() +"&storeId=" + (SharedPreferencesUtils.getParam(this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0) + "") +  "&infoId=" + infoId
//        );
        webViewRequestParam.setTitle("公告");
        Intent intent = new Intent(this, ProjectDetailsWebviewActivity.class);
        intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, webViewRequestParam);
        //设置想要展示的数据内容
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this,
                requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        int smallIcon = R.mipmap.app_icon;
        String body = JsonUtil.getJsonValuesString(data, "body");
        String ticker = "您有一条新通知";
        String title = "门店新增加了公告";
        String content = body.substring(data.indexOf(":") > 0 ? body.indexOf(":") + 1 : 0, body.length());

        //实例化工具类，并且调用接口
        NotifyUtil notify1 = new NotifyUtil(MainActivity.this, 1);
        notify1.notify_normal_singline(pIntent, smallIcon, ticker, title, content, true, true, false);
//        currentNotify = notify1;
    }

    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            MyLog.e("hep-onMessageReceived", messages.size() + "");
            for (EMMessage emMessage : messages) {
                if ("bulletin".equals(emMessage.getStringAttribute(MessageHelper.MESSAGE_EXT_CUSTOM_TYPE, null))) {
                    String data = emMessage.getStringAttribute(MessageHelper.MESSAGE_EXT_DATA, null);
                    notify_normal_singLine(data);
                }
                MyLog.e("hep----","==="+ emMessage.getStringAttribute(MessageHelper.MESSAGE_EXT_CUSTOM_TYPE, null));
                MyLog.e("hep----", "==="+emMessage.getStringAttribute(MessageHelper.MESSAGE_EXT_FROM_TYPE, null));
            }

            // notify new message
            /*for (EMMessage message : messages) {
                MessageHelper.getInstance().getNotifier().onNewMsg(message);
            }*/
            refreshUIWithMessage();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //red packet code : 处理红包回执透传消息
            /*for (EMMessage message : messages) {
                EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
                final String action = cmdMsgBody.action();//获取自定义action
                if (action.equals(RedPacketConstant.REFRESH_GROUP_RED_PACKET_ACTION)) {
                    RedPacketUtil.receiveRedPacketAckMessage(message);
                }
            }*/
            //end of red packet code
            MyLog.e("hep-onCmdMessageReceived", messages.size() + "");
            refreshUIWithMessage();
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
//            MyLog.e("hep-onMessageChanged", );
        }
    };
    EMGroupChangeListener groupChangeListener = new EMGroupChangeListener() {
        @Override
        public void onInvitationReceived(String s, String s1, String s2, String s3) {

        }

        @Override
        public void onRequestToJoinReceived(String s, String s1, String s2, String s3) {

        }

        @Override
        public void onRequestToJoinAccepted(String s, String s1, String s2) {

        }

        @Override
        public void onRequestToJoinDeclined(String s, String s1, String s2, String s3) {

        }

        @Override
        public void onInvitationAccepted(String s, String s1, String s2) {

        }

        @Override
        public void onInvitationDeclined(String s, String s1, String s2) {

        }

        @Override
        public void onUserRemoved(String s, String s1) {

        }

        @Override
        public void onGroupDestroyed(String s, String s1) {
            refreshUIWithMessage();
        }

        @Override
        public void onAutoAcceptInvitationFromGroup(String s, String s1, String s2) {

        }
    };

    private void refreshUIWithMessage() {
        runOnUiThread(new Runnable() {
            public void run() {
                // refresh unread count
                updateUnreadLabel();
                if (currentIndex == 1) {
                    // refresh conversation list
                    RxBus.getDefault().post(Constants.RXBUS_CODE_REFRESH_MESSAGE, "refresh");
                }
            }
        });
    }

    /**
     * update unread message count
     */
    public void updateUnreadLabel() {
        if (badge != null) {
            badge.setBadgeNumber(getUnreadMsgCountTotal());
        }
    }

    /**
     * get unread message count
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMessageCount();

        return unreadMsgCountTotal;
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE}, 0);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 0) {
            if ((grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
                PushManager.getInstance().initialize(this.getApplicationContext(), GetuiPushService.class);
            } else {
                Log.e("King", "We highly recommend that you need to grant the special permissions before initializing the SDK, otherwise some "
                        + "functions will not work");
                PushManager.getInstance().initialize(this.getApplicationContext(), GetuiPushService.class);
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void onTabChanged(String tabId) {
        switch (tabId) {
            case "商城":
                if(refreshShopping){
                    RxBus.getDefault().post(Constants.REFRESH_SHOPPING, new CommonEvent("商城刷新"));
                }
                MyLog.e("yang", "商城");
                break;
            case "消息":
//            case "门店":
            case "我的":
                if (!checkLoginState()) {
                    if (mTabHost != null) {
                        mTabHost.setCurrentTab(currentIndex);
                    }
                    return;
                }
                break;
        }

        updateTabState();
    }

    @Subscribe(code = Constants.RXBUS_CODE_SWITCH_MAIN_TAB, threadMode = ThreadMode.MAIN)
    public void switchMainTab(final CommonEvent event) {
        final String msg = event.getMsg();
        MyLog.e("yang", "msg===" + msg);
        mTabHost.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(!TextUtils.isEmpty(msg)){
                    if (msg.equals("登录未绑定")) {
                        isNeedBind = true;
                        mTabHost.setCurrentTab(2);
                        MyLog.e("yang","登录未绑定登录未绑定登录未绑定登录未绑定登录未绑定");
                    } else if (msg.equals("登录绑定")) {
                        mTabHost.setCurrentTab(2);
                    } else {
                        mTabHost.setCurrentTab(0);
                    }
                }else {
                    mTabHost.setCurrentTab(0);
                }


            }
        }, 400);


    }

    /**
     * 更新Tab 的状态
     */
    private void updateTabState() {
        TabWidget tabWidget = mTabHost.getTabWidget();
        for (int i = 0; i < tabWidget.getTabCount(); i++) {
            View view = tabWidget.getChildTabViewAt(i);
            ImageView tabIcon = (ImageView) view.findViewById(R.id.tab_image);
            TextView tabText = (TextView) view.findViewById(R.id.tab_title);
            if (i == mTabHost.getCurrentTab()) {
                currentIndex = i;
                tabIcon.setImageResource(DataGenerator.mTabResPressed[showFragmentIndex.get(i)]);
                tabText.setTextColor(getResources().getColor(R.color.appThemeColor));
            } else {
                tabIcon.setImageResource(DataGenerator.mTabRes[showFragmentIndex.get(i)]);
                tabText.setTextColor(getResources().getColor(R.color.appThemeTitleColor));
            }
        }
    }

    private void selectedStoreId() {
        try {
            List<Integer> list = new ArrayList<>();
            List<ChainStoresModel> mChainStoresList = UserHelper.getInstance().getmChainStoresList(MainActivity.this);
            if (mChainStoresList != null && mChainStoresList.size() > 0) {
                for (int i = 0; i < mChainStoresList.size(); i++) {
                    int storeId = mChainStoresList.get(i).getStoreId();
                    list.add(storeId);
                }
            }


            int bindStoreId = (int) SharedPreferencesUtils.getParam(MainActivity.this, UserHelper.getInstance().getUserAccount() + Constants.SHARED_PREFERENCES_KEY_BINDSTOREID, 0);
            if (bindStoreId != 0) {
                if (list != null && list.size() > 0) {
                    if (list.contains(bindStoreId)) {
                        UserHelper.getInstance().setSelectStoreId(MainActivity.this, bindStoreId);
                    } else {
                        UserHelper.getInstance().setSelectStoreId(MainActivity.this, UserHelper.getInstance().getOwnerInfoModel(MainActivity.this).getBindStoreId());
                    }
                } else {
                    UserHelper.getInstance().setSelectStoreId(MainActivity.this, bindStoreId);
                }
            } else {
                UserHelper.getInstance().setSelectStoreId(MainActivity.this, UserHelper.getInstance().getOwnerInfoModel(MainActivity.this).getBindStoreId());
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateUnreadLabel();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                PhoneUtils.ShowToastMessage(MainActivity.this, getString(R.string.key_back_tips));
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                MobclickAgent.onKillProcess(MainActivity.this);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);
        isMainActivity = false;
        isNeedBind = false;
        refreshShopping = false;
        if (null != locationClient) {
            locationClient.stopLocation();
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    //  定位回调监听事件
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private double longItude;
    private double latItude;
    private boolean isFirstLoc = true;
    AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {

            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    if (isFirstLoc) {
                        longItude = amapLocation.getLongitude();
                        latItude = amapLocation.getLatitude();
                        MyLog.e("yang","longItude=="+longItude+"....latItude=="+latItude);
                        MyLog.e("yang", "定位成功");
                        isFirstLoc = false;
                        bigDataAppInfo();
                    }
                } else {
                    if(isFirstLoc){
                        isFirstLoc = false;
                        bigDataAppInfo();
                    }
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    MyLog.e("yang", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };

    //定位初始化控件配置
    private void initLoc() {
        locationClient = new AMapLocationClient(MainActivity.this);
        //设置定位回调监听
        locationClient.setLocationListener(mAMapLocationListener);
        //初始化定位参数
        locationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        locationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        locationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        locationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        locationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        locationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        locationClient.setLocationOption(locationOption);
        //启动定位
        locationClient.startLocation();

    }
}
